/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.gateway.server.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.base.domain.constant.CommonConstant.NumberConstant;
import com.iwindplus.base.util.HttpsUtil;
import com.iwindplus.base.util.JacksonUtil;
import com.iwindplus.base.util.ReactorUtil;
import com.iwindplus.base.util.UrlUtil;
import com.iwindplus.base.util.domain.dto.ReactorResponseDTO;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.FilterConstant;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.ServerWebExchangeContextConstant;
import com.iwindplus.gateway.server.domain.property.GatewayProperty;
import com.iwindplus.gateway.server.domain.property.GatewayProperty.LogConfig;
import com.iwindplus.gateway.server.util.GatewayUtil;
import com.iwindplus.log.domain.dto.GatewayLogDTO;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
 * 日志过滤器.
 *
 * @author zengdegui
 * @since 2020/4/15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LogFilter implements Ordered, GlobalFilter {

    private final GatewayProperty property;

    @Override
    public int getOrder() {
        return FilterConstant.FILTER_LOG_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 提前判断是否需要采样 / 白名单
        if (skip(exchange)) {
            return chain.filter(exchange);
        }

        final long start = System.nanoTime();

        final LogConfig cfg = property.getLog();
        // 1. 提前决定是否需要采样响应体，避免后面反复判断
        final boolean needRespBody = Boolean.TRUE.equals(cfg.getEnabledResponseBody());

        // 2. 构造“日志实体”冷流，cache 保证多次订阅只构建一次
        Mono<GatewayLogDTO> logDto = Mono.defer(() -> GatewayUtil.buildGatewayLog(exchange, cfg))
            .cache();

        // 3. 主链：filter -> 录日志 -> 打印耗时
        Mono<Void> main;
        if (needRespBody) {
            main = ReactorUtil.readResponseBody(exchange, chain::filter)
                .doOnNext(collector -> buildResponse(cfg, collector, logDto))
                .then();
        } else {
            main = chain.filter(exchange);
        }

        return main.then(
                logDto.publishOn(Schedulers.boundedElastic())
                    .doOnNext(GatewayUtil::asyncPublishGatewayLog)
                    .onErrorResume(e -> {
                        log.warn("async publish gateway log error: {}", e.getMessage());
                        return Mono.empty();
                    })
            )
            .doFinally(signal -> log.info("{} execute cost={} ms", this.getClass().getSimpleName(),
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)))
            .then();
    }

    private boolean skip(ServerWebExchange exchange) {
        final LogConfig cfg = property.getLog();
        if (!cfg.getEnabled()) {
            return true;
        }

        // 白名单标记
        final Boolean whited = ReactorUtil.getAttribute(exchange, ServerWebExchangeContextConstant.WHITED_FLAG);
        if (Boolean.TRUE.equals(whited)) {
            return true;
        }

        // 路径忽略
        final String requestPath = exchange.getRequest().getPath().value();
        if (this.hasIgnoredWhitedFlag(requestPath)) {
            return true;
        }

        // 采样率
        if (!HttpsUtil.checkSampleRateInRange(cfg.getSampleRate())) {
            return true;
        }

        return false;
    }

    private boolean hasIgnoredWhitedFlag(String requestPath) {
        List<String> ignoredPatterns = property.getLog().getIgnoredApi();
        if (CollUtil.isNotEmpty(ignoredPatterns)) {
            List<String> whiteList = ignoredPatterns.stream().filter(Objects::nonNull).distinct().toList();
            return UrlUtil.isMatchLike(whiteList, requestPath);
        }
        return false;
    }

    private void buildResponse(LogConfig cfg, ReactorResponseDTO collector, Mono<GatewayLogDTO> logDto) {
        logDto.subscribe(entity -> {
            entity.setResponseStatus(collector.getResponseStatus());
            if (cfg.getEnabledResponseHeader()) {
                entity.setResponseHeaders(JacksonUtil.toJsonStr(collector.getResponseHeaders()));
            }
            if (cfg.getEnabledResponseBody()) {
                String body = collector.getResponseBody();
                if (CharSequenceUtil.isNotBlank(body)) {
                    entity.setResponseBody(CharSequenceUtil.maxLength(body,
                        cfg.getLimitResponseBody() * NumberConstant.NUMBER_ONE_THOUSAND_TWENTY_FOUR));
                }
            }
        });
    }

}